package com.mayisoftware.mayioa.business.plan.impl.controller;


import com.mayisoftware.mayioa.business.plan.api.domain.PlanFlowInfo;
import com.mayisoftware.mayioa.business.plan.api.service.IPlanFlowService;
import com.mayisoftware.mayioa.common.api.annotation.Log;
import com.mayisoftware.mayioa.common.api.base.AjaxResult;
import com.mayisoftware.mayioa.common.api.enums.BusinessType;
import com.mayisoftware.mayioa.common.impl.config.Global;
import com.mayisoftware.mayioa.common.impl.utils.StringUtils;
import com.mayisoftware.mayioa.platform.api.domain.SysUser;
import com.mayisoftware.mayioa.platform.impl.util.FileUploadUtils;
import com.mayisoftware.mayioa.platform.impl.util.ShiroUtils;
import com.mayisoftware.mayioa.platform.impl.web.base.BaseController;
import com.mayisoftware.mayioa.platform.impl.web.page.TableDataInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/plan/flow")
public class PlanFlowController extends BaseController{
    /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(PlanFlowController.class);

    /**
     * 日志流程服务
     */
    @Autowired
    private IPlanFlowService planFlowService;

    /**
     * 流程部署服务
     */
    @Autowired
    private RepositoryService repositoryService;
    /**
     * 页面前缀
     */
    private String prefix = "plan/flow";

    @RequiresPermissions("plan:flow:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/flow";
    }

    /**
     * 保存头像
     */
    @Log(title = "计划流程上传", businessType = BusinessType.IMPORT)
    @PostMapping("/uploadfile")
    @ResponseBody
    public AjaxResult uploadfile( @RequestParam("file") MultipartFile file)
    {
        InputStream inputStream = null;
        XMLStreamReader reader = null;
        try
        {
            if (!file.isEmpty())
            {
                String fileName = file.getOriginalFilename();
                String planData = FileUploadUtils.upload(Global.getPlanFlowPath(), file);
                SysUser user = ShiroUtils.getSysUser();
                log.error("上传文件:"+planData);

                PlanFlowInfo planFlowInfo = new PlanFlowInfo();
                String filePath = Global.getPlanFlowPath()+planData;
                planFlowInfo.setPlanFlowFilePath(filePath.replace("\\","/"));
                planFlowInfo.setPlanFlowFileName(fileName);
                planFlowInfo.setPlanFlowUploadUserId(user.getUserId().intValue());
                planFlowInfo.setPlanFlowUploadTime(new Date());

                //解析BPMN模型看是否成功
                inputStream = new FileInputStream(new File(filePath));
                BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
                XMLInputFactory factory= XMLInputFactory.newInstance();
                reader = factory.createXMLStreamReader(inputStream);
                BpmnModel model = bpmnXMLConverter.convertToBpmnModel(reader);
                List<Process> processes =model.getProcesses();
                Process curProcess = null;
                if (CollectionUtils.isEmpty(processes)){
                    return  error("BPMN模型没有配置流程");
                }

                curProcess = processes.get(0);

                planFlowInfo.setPlanFlowId(curProcess.getId());
                planFlowInfo.setPlanFlowName(curProcess.getName());
                planFlowInfo.setPlanFlowParseStatus(1);
                inputStream = new FileInputStream(new File(filePath));
                DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().name("mayioa_PLAN_FLOW")
                        .addInputStream(filePath,inputStream);

                Deployment deployment= deploymentBuilder.deploy();
                log.info("部署:"+deployment);
                return toAjax(planFlowService.addFlowRecord(planFlowInfo));
            }

            return error("文件没提交");
        }
        catch (Exception e)
        {
            log.error("上传文件失败！", e);
            return error("流程文件上传异常！"+e.getMessage());
        }
        finally {
            try {
                if (reader !=null){
                    reader.close();
                }
            } catch (Exception e) {
                log.error("关闭异常",e);
            }

            IOUtils.closeQuietly(inputStream);
        }
    }


    @RequiresPermissions("plan:flow:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PlanFlowInfo record)
    {
        startPage();
        List<PlanFlowInfo> list = planFlowService.queryRecordList(record);
        return getDataTable(list);
    }

    /**
     * 新增计划
     */
    @RequiresPermissions("plan:flow:add")
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        return prefix + "/add";
    }

}
